package cn.edu.scnu.semart.message.task;

import cn.edu.scnu.semart.model.chat.ChatMessage;
import cn.edu.scnu.semart.message.service.ChatMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.List;

@Component
public class ChatMessagePersistTask {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ChatMessageService chatMessageService;

    // 每天凌晨2点执行
//    @Scheduled(cron = "0 0 2 * * ?")
    // 每分钟执行一次（开发测试用）
    @Scheduled(cron = "0 * * * * ?")
    public void persistChatMessages() {
        Set<String> keys = redisTemplate.keys("chat:msg:*");
        if (keys != null) {
            for (String key : keys) {
                List<ChatMessage> messages = chatMessageService.getMessagesFromRedis(key);
                if (messages != null && !messages.isEmpty()) {
                    chatMessageService.saveMessagesToMySQL(messages);
                    chatMessageService.removeMessagesFromRedis(key);
                }
            }
        }
    }
} 